package com.example.mybatisplusdemo.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.mybatisplusdemo.common.utls.SessionUtils;
import com.example.mybatisplusdemo.mapper.UserMapper;
import com.example.mybatisplusdemo.model.domain.Product;
import com.example.mybatisplusdemo.model.dto.*;
import com.example.mybatisplusdemo.model.vo.UserVO;
import com.example.mybatisplusdemo.service.IRechargeService;
import lombok.val;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.mybatisplusdemo.common.JsonResponse;
import com.example.mybatisplusdemo.service.IUserService;
import com.example.mybatisplusdemo.model.domain.User;

import java.time.LocalDateTime;


/**
 *
 *  前端控制器
 *
 *
 * @author lqj
 * @since 2025-06-22
 * @version v1.0
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    private final Logger logger = LoggerFactory.getLogger( UserController.class );

    @Autowired
    private IUserService userService;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JdbcOperations jdbcTemplate;

    @Autowired
    private IRechargeService rechargeService;

    /**
     * 描述：根据Id 查询
     *
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse<User> getById(@PathVariable("id") Long id)throws Exception {
        User user = userService.getById(id);
        return JsonResponse.success(user);
    }

    @GetMapping("getId")
    public User getUserById(String username){
        User user = userMapper.selectByName(username);
        return user;
    }

    @GetMapping("getAddresses")
    public User getAddressesByUsername(User u){
        UserVO user = (UserVO) userMapper.selectAddressesByName(u.getUsername());
        return user;
    }

    @PostMapping("test")
    public User getUserByNamePost(User user){
        User user1 = userMapper.selectByName(user.getUsername());
        return user1;
    }

    @GetMapping("count")
    public JsonResponse<Long> getUserById()throws Exception {
        Long count= userService.count();
        return JsonResponse.success(count);
    }

    @PostMapping("login")
    public JsonResponse login(@RequestBody User user)throws Exception{
        User login = userService.login(user);
        return JsonResponse.success(login);
    }

    @PostMapping("addUser")
    public JsonResponse addProduct(@RequestBody User user) {
        boolean save = userService.save(user);
        return save
                ? JsonResponse.success("用户添加成功")
                : JsonResponse.failure("用户添加失败");
    }

    @GetMapping("userPageList")
    public JsonResponse<Page<Product>> selectPageList(User user, UserPageDTO userPageDTO) {
        Page<Product> page = userService.pageList(user, userPageDTO);
        return JsonResponse.success(page);
    }

    @PutMapping("/update")
    public JsonResponse<?> update(@RequestBody User user) {
        if (user == null || user.getId() == null) {
            return JsonResponse.failure("参数错误");
        }

        // 不允许修改字段清除
        // 不允许修改字段清除
        user.setPassword(null);
        user.setDeleted(null);
        user.setLevelId(null);
        user.setDiscountRate(null);
        user.setPointsMultiplier(null);
        user.setBalance(null);
        user.setPoints(null);
        user.setTotalConsumption(null);

        user.setUpdateTime(LocalDateTime.now());
        userService.updateById(user);
        return JsonResponse.success("更新成功");
    }

    // 用户注册接口
    @PostMapping("register")
    public JsonResponse<String> register(@RequestBody RegisterDTO registerDTO) {
        // 基础验证
        if (!StringUtils.hasText(registerDTO.getUsername())) {
            return JsonResponse.failure("用户名不能为空");
        }

        if (!StringUtils.hasText(registerDTO.getPassword())) {
            return JsonResponse.failure("密码不能为空");
        }

        // 检查用户名是否已存在
        String checkUsernameSql = "SELECT COUNT(*) FROM user WHERE username = ?";
        Integer count = jdbcTemplate.queryForObject(checkUsernameSql, Integer.class, registerDTO.getUsername());
        if (count != null && count > 0) {
            return JsonResponse.failure("用户名已被使用");
        }

        // 插入用户数据
        // 注释用来检测是否可以提交
        String insertUserSql = "INSERT INTO user (username, password, mobile) VALUES (?, ?, ?)";
        int rowsAffected = jdbcTemplate.update(insertUserSql, registerDTO.getUsername(), registerDTO.getPassword(), registerDTO.getMobile());

        // 返回注册结果
        return rowsAffected > 0 ? JsonResponse.success("注册成功") : JsonResponse.failure("注册失败，请重试");
    }
    @DeleteMapping("/delete/{id}")
    public JsonResponse<?> deleteUser(@PathVariable Long id) {
        if (id == null) {
            return JsonResponse.failure("参数错误");
        }

        boolean success = userService.removeById(id); // MyBatis-Plus 自动逻辑删除
        return success ? JsonResponse.success("删除成功") : JsonResponse.failure("删除失败");
    }
    @PutMapping("resetPassword/{id}")
    public JsonResponse<?> resetPassword(@PathVariable Long id) {
        User user = new User();
        user.setId(id);
        user.setPassword("123456"); // 默认密码
        boolean success = userService.updateById(user);
        return success ? JsonResponse.success("重置成功") : JsonResponse.failure("重置失败");
    }

    @PostMapping("/updateLevel")
    public JsonResponse updateLevel(@RequestBody @Validated UpdateLevelRequestDTO req) {
        User user = userService.getById(req.getUserId());
        if (user == null) {
            return JsonResponse.failure("用户不存在");
        }

        user.setLevelId(req.getLevelId());
        user.setDiscountRate(req.getDiscountRate());
        user.setPointsMultiplier(req.getPointsMultiplier());
        user.setCanReturnWithoutReview(req.getCanReturnWithoutReview());
        //user.setTotalConsumption(req.getTotalConsumption());

        userService.updateById(user);
        return JsonResponse.success("等级更新成功");
    }


}

